"""
系统管理API蓝图
提供健康检查、文件清理等系统管理功能
"""

from flask import Blueprint, request, jsonify, current_app
import logging
from app.tools.utils import get_system_info, cleanup_old_files
from app.service.system_service import system_service

# 创建系统API蓝图
system_bp = Blueprint('system', __name__, url_prefix='/system')

@system_bp.route('/health', methods=['GET'])
def health_check():
    """健康检查接口"""
    try:
        system_info = get_system_info()
        return jsonify({
            'status': 'healthy', 
            'message': '视频工具服务运行正常',
            'system_info': system_info
        })
    except Exception as e:
        logging.error(f"健康检查失败: {e}")
        return jsonify({'status': 'error', 'message': str(e)}), 500

@system_bp.route('/cleanup', methods=['POST'])
def cleanup_files():
    """清理临时文件"""
    try:
        cleanup_old_files(current_app.config['UPLOAD_FOLDER'])
        cleanup_old_files(current_app.config['OUTPUT_FOLDER'])
        
        return jsonify({'message': '文件清理完成'})
    
    except Exception as e:
        logging.error(f"文件清理失败: {e}")
        return jsonify({'error': str(e)}), 500

@system_bp.route('/fonts', methods=['GET'])
def get_fonts():
    """获取系统支持的字体列表"""
    try:
        # 获取查询参数
        language = request.args.get('language', 'zh')
        include_test = request.args.get('include_test', 'false').lower() == 'true'
        
        if include_test:
            # 包含字体渲染测试的完整信息
            font_info = system_service.get_system_font_info()
            return jsonify({
                'status': 'success',
                'message': '获取字体信息成功',
                'data': font_info
            })
        else:
            # 仅返回可用字体列表
            available_fonts = system_service.get_available_fonts()
            return jsonify({
                'status': 'success',
                'message': '获取字体列表成功',
                'data': {
                    'fonts': available_fonts,
                    'recommended_fonts': {
                        'zh': system_service.get_recommended_font('zh'),
                        'en': system_service.get_recommended_font('en'),
                        'ja': system_service.get_recommended_font('ja'),
                        'ko': system_service.get_recommended_font('ko')
                    }
                }
            })
    
    except Exception as e:
        logging.error(f"获取字体列表失败: {e}")
        return jsonify({'status': 'error', 'message': str(e)}), 500

@system_bp.route('/fonts/<font_key>', methods=['GET'])
def get_font_info(font_key):
    """获取指定字体的详细信息"""
    try:
        font_info = system_service.get_font_info(font_key)
        
        if font_info is None:
            return jsonify({
                'status': 'error',
                'message': f'字体 {font_key} 不存在'
            }), 404
        
        return jsonify({
            'status': 'success',
            'message': '获取字体信息成功',
            'data': font_info
        })
    
    except Exception as e:
        logging.error(f"获取字体信息失败: {e}")
        return jsonify({'status': 'error', 'message': str(e)}), 500

@system_bp.route('/fonts/recommended', methods=['GET'])
def get_recommended_font():
    """获取推荐字体"""
    try:
        language = request.args.get('language', 'zh')
        font_path = system_service.get_recommended_font(language)
        
        if font_path is None:
            return jsonify({
                'status': 'error',
                'message': f'未找到适合语言 {language} 的字体'
            }), 404
        
        return jsonify({
            'status': 'success',
            'message': '获取推荐字体成功',
            'data': {
                'language': language,
                'font_path': font_path
            }
        })
    
    except Exception as e:
        logging.error(f"获取推荐字体失败: {e}")
        return jsonify({'status': 'error', 'message': str(e)}), 500

@system_bp.route('/fonts/test', methods=['POST'])
def test_font_rendering():
    """测试字体渲染功能"""
    try:
        data = request.get_json()
        font_path = data.get('font_path')
        
        if not font_path:
            return jsonify({
                'status': 'error',
                'message': '缺少字体路径参数'
            }), 400
        
        # 测试字体渲染
        test_result = system_service.test_font_rendering(font_path)
        
        return jsonify({
            'status': 'success',
            'message': '字体渲染测试完成',
            'data': {
                'font_path': font_path,
                'rendering_success': test_result
            }
        })
    
    except Exception as e:
        logging.error(f"字体渲染测试失败: {e}")
        return jsonify({'status': 'error', 'message': str(e)}), 500 